package com.ljh.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ljh.common.lang.Result;
import com.ljh.entity.Tag;
import com.ljh.entity.Type;
import com.ljh.service.TagService;
import com.ljh.service.TypeService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 关注公众号：MarkerHub
 * @since 2021-07-29
 */
@RestController
public class TagController {
    @Autowired
    TagService tagService;



    @GetMapping("/tag")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {

        Page page = new Page(currentPage, 500);
        IPage pageData = tagService.page(page, new QueryWrapper<Tag>().orderByDesc("id"));

        return Result.succ(pageData);
    }


    @RequiresAuthentication
    @PostMapping("/tag/add")
    public Result add(@Validated @RequestBody Tag tag) {

        Tag temp = null;
        if(tag.getId() != null) {
            temp = tagService.getById(tag.getId());
            temp.setCount(tag.getCount()+1);
        } else {
            temp = new Tag();
            temp.setCount(tag.getCount());
            temp.setTag(tag.getTag());
        }
        tagService.saveOrUpdate(temp);
        return Result.succ(null);
    }

    @RequiresAuthentication
    @PostMapping("/tag/sub")
    public Result sub(@Validated @RequestBody Tag tag) {
        Tag temp = null;
        if(tag.getId() != null) {
            temp = tagService.getById(tag.getId());
            temp.setCount(tag.getCount() == 0? 0 : (tag.getCount()-1));
        } else {
            temp = new Tag();
            temp.setCount(tag.getCount());
            temp.setTag(tag.getTag());
        }
        tagService.saveOrUpdate(temp);
        return Result.succ(null);
    }

    @PostMapping("/tag/delete/{id}")
    @ResponseBody
    public Result del(@PathVariable(name = "id") Long id){
        boolean result = tagService.removeById(id);
        if(result == true){
            return Result.succ(null);

        }else {
            return Result.fail(null);
        }
    }

    @PostMapping("/tag/search")
    public Result Search(@Validated @RequestBody Tag tag) {
        Page page = new Page(1, 500);
        IPage pageData = tagService.page(page, new QueryWrapper<Tag>().like("tag", tag.getTag()));

        return Result.succ(pageData);
    }
}
